package com.observer;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * 观察者 AObserver,当被观察者BObservered发生变化时通知观察者改变状态
 * 
 * @author sh04799
 *
 */
public class AObserver implements Observer {

	
	@Override
	public void update(Observable o, Object arg) {
		System.out.println("观察者 update(Observable o, Object arg)==" + arg);
		for (Listener observerListener : list) {
			observerListener.onCreate(arg);
		}

	}
	private static AObserver instance;
	private AObserver(){
		BObservered.getInstance().addObserver(this);
	}
	public static AObserver getInstance() {
		if (instance == null) {
			instance = new AObserver();
		}
		return instance;
	}

	List<Listener> list = new ArrayList<>();
	Object lock = new Object();

	public void addObserver(Listener listener) {
		if (listener != null) {
			synchronized (lock) {
				if (!list.contains(listener)) {
					list.add(listener);
				}
			}
		}

	}
	public void removeObserver(Listener listener){
		synchronized (lock) {
		list.remove(listener);	
		}
	}

}
